package com.yocard.yxyd.ui.presenter;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.v4.app.Fragment;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.webkit.ValueCallback;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yocard.yxyd.utils.util.ConvertUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yocard.yxyd.R;
import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.base.CommonSubscriber;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.base.RxPresenter;
import com.yocard.yxyd.http.HttpManager;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.http.model.response.UserInfoBean;
import com.yocard.yxyd.others.ClassicsHeader;
import com.yocard.yxyd.others.GifSizeFilter;
import com.yocard.yxyd.others.Glide4Engine;
import com.yocard.yxyd.ui.contract.MeContract;
import com.yocard.yxyd.ui.dialog.CommonDialog;
import com.yocard.yxyd.ui.dialog.OpenwxDialog;
import com.yocard.yxyd.utils.CommonUtils;
import com.yocard.yxyd.utils.RxUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONObject;

import java.io.File;

import javax.inject.Inject;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created on 2019/4/8.
 */
public class MePresenter extends RxPresenter<MeContract.View> implements MeContract.Presenter {
    int headHeight;
    @Inject
    public MePresenter(HttpManager manager) {
        super(manager);
    }

    @Override
    public void fetchUserData() {
        addSubscribe(httpManager.getUswrInfo()
                .compose(RxUtil.rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<UserInfoBean>(mView) {

                    @Override
                    public void onSuccess(UserInfoBean data) {
                        try {
                            mView.onFetchUser(data);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }));
    }

    @Override
    public void openWx(String wx) {
        // 获取系统剪贴板
        ClipboardManager clipboard = (ClipboardManager) mView.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText(null, wx);
        clipboard.setPrimaryClip(clipData);

        OpenwxDialog dialog = new OpenwxDialog(mView.getContext(), s -> {
            if(!CommonUtils.isWeixinAvilible(mView.getContext())) {
                ToastUtils.showShort(R.string.we_chat_not_install);
                return;
            }
            Intent intent = new Intent();
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            mView.getContext().startActivity(intent);
        });
        dialog.show();
    }

    @Override
    public void showContact() {
        String service = mView.getContext().getResources().getString(R.string.service_phone);
        CommonDialog.Builder builder = new CommonDialog.Builder(mView.getContext()).setTitle(service)
                .setLeftText("取消")
                .setRightText("拨打")
                .setLogo(R.mipmap.ic_wode_kefu_call)
                .setListener(pos -> {
                    if (pos == CommonDialog.CLICK_POS_RIGHT) {
                        CommonUtils.callPhone(mView.getContext(), service);
                    }
                });
        builder.show();
    }

    @Override
    public void selectAvator(Fragment activity, int requestCode) {
        CommonDialog.Builder builder = new CommonDialog.Builder(mView.getContext()).setTitle("是否去选择头像")
                .setLeftText("取消")
                .setRightText("确定")
                .setListener(pos -> {
                    if (pos == CommonDialog.CLICK_POS_RIGHT) {
                        try {
                            toGllery(activity, requestCode);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        builder.show();
    }

    @Override
    public void LayoutText(String status, TextView textView) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
        if (Constants.AUTH_APPROVED.equals(status)) {
            layoutParams.rightMargin = ConvertUtils.dp2px(14);
        } else {
            layoutParams.rightMargin = ConvertUtils.dp2px(34);
        }

        textView.setLayoutParams(layoutParams);
    }

    @SuppressLint("CheckResult")
    @Override
    public void uploadAvator(String fileUrl) {
        addSubscribe(Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                //压缩反而占用大量内存，oom
//                File file = CommonUtils.saveImg(fileUrl, type);
                File file = CommonUtils.saveImg(Constants.DEFAULT_PIC_SIZE, fileUrl, "portrait");
                emitter.onNext(file);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(file -> {
                    addSubscribe(httpManager.uploadAvator(file)
                            .compose(RxUtil.rxSchedulerHelper())
                            .subscribeWith(new CommonSubscriber<CommonBean>(mView) {
                                @Override
                                public void onSuccess(CommonBean data) {
                                    addAvatorId(data.getId());
                                }
                            }));
                }));
    }

    @Override
    public void showShare(String url,String platform) {
        final OnekeyShare oks = new OnekeyShare();
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform);
        }
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle("优单");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("海量优质客户等你来抢");
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {
                shareParams.setText("海量优质客户等你来抢");
                shareParams.setTitle("优单-信贷经理展业神器，海量真实优质客户");
                shareParams.setTitleUrl(url);
                shareParams.setUrl(url);
                shareParams.setImageData(BitmapFactory.decodeResource(AppContext.getContext().getResources(),R.mipmap.ico_share));
                shareParams.setShareType(Platform.SHARE_WEBPAGE);
            }
        });
        oks.show(mView.getContext());
    }

    @Override
    public void setUpelasHead(RelativeLayout rlHeadLayout, ClassicsHeader classicsHeader) {
        rlHeadLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                headHeight = rlHeadLayout.getHeight();
                rlHeadLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

        ViewGroup.LayoutParams layoutParams = rlHeadLayout.getLayoutParams();
        ValueCallback<Integer> callback = new ValueCallback<Integer>() {
            @Override
            public void onReceiveValue(Integer value) {
                layoutParams.height = headHeight + value;
                rlHeadLayout.requestLayout();
            }
        };
        classicsHeader.setCallback(callback);
    }

    private void addAvatorId(String id) {
        addSubscribe(httpManager.addAvatorId(id)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<JSONObject>(mView) {
                    @Override
                    public void onSuccess(JSONObject data) {
                        mView.showErrorMsg("头像上传成功");
                    }
                }));
    }

    private void toGllery(Fragment activity, int requestCode) {
        AndPermission.with(AppContext.getContext())
                .runtime()
                .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .onGranted(permissions -> {
                    Matisse.from(activity)
                            .choose(MimeType.ofImage())
                            .theme(R.style.Matisse_Dracula)
                            .countable(false)
                            .capture(true) //是否提供拍照功能
                            .captureStrategy(new CaptureStrategy(true,mView.getContext().getPackageName() + ".fileprovider"))//存储到哪里
                            .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                            .maxSelectable(1)
                            .originalEnable(true)
                            .maxOriginalSize(10)
                            .imageEngine(Glide4Engine.getInstance())
                            .forResult(requestCode);
                })
                .onDenied(permissions -> {
                    ToastUtils.showLong("请授予APP相应权限");
                })
                .start();
    }
}
